package com.jl.encrypt;

import cn.hutool.json.JSONUtil;
import com.jl.encrypt.annotate.JLEncode;
import com.jl.encrypt.config.SecretKeyConfig;
import com.jl.encrypt.util.JLAES;
import com.jl.encrypt.util.JLRSA;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * json返参拦截
 */
@Slf4j
@ControllerAdvice
public class JLResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private boolean encrypt;

    @Autowired
    private SecretKeyConfig secretKeyConfig;

    private static ThreadLocal<Boolean> encryptLocal = new ThreadLocal<>();

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        encrypt = false;
        if (returnType.getMethod().isAnnotationPresent(JLEncode.class) && secretKeyConfig.isOpen()) {
            encrypt = true;
        }
        return encrypt;
    }

    @Override
    @SneakyThrows
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Boolean status = encryptLocal.get();
        if (null != status && !status) {
            encryptLocal.remove();
            return body;
        }
        if (encrypt) {
            String content = JSONUtil.toJsonStr(body);
            String result;
            if (secretKeyConfig.getAes() == null) {
                result = JLRSA.privateEncode(content, secretKeyConfig.getRsa().getPrivateKey());
            } else {
                result = JLAES.encode(content, secretKeyConfig.getAes().getKey());
            }
            if (secretKeyConfig.isShowLog()) {
                log.info("原文参数：{}，加密后参数：{}", content, result);
            }
            return result;
        }
        return body;
    }
}
